/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-12-13 10:53:38
 * @LastEditTime: 2022-12-13 11:26:11
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
 */
import axios from "axios";
import type { AxiosRequestConfig, AxiosError, AxiosResponse } from "axios";
const service = axios.create({
  baseURL: "http://127.0.0.1:4523/m1/2075777-0-default",
});
/* 请求拦截器 */
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    //  伪代码
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`;
    // }
    return config;
  },
  (error: AxiosError) => {
    alert(error.message);
    return Promise.reject(error);
  }
);
/* 响应拦截器 */
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message, data } = response.data;
    console.log(code, message, data);

    // 根据自定义错误码判断请求是否成功
    if (code === 0 || code === "0") {
      // 将组件用的数据返回
      return data;
    } else {
      // 处理业务错误。
      alert(message);
      return Promise.reject(new Error(message));
    }
  },
  (error: AxiosError) => {
    // 处理 HTTP 网络错误
    let message = "";
    // HTTP 状态码
    const status = error.response?.status;
    switch (status) {
      case 401:
        message = "token 失效，请重新登录";
        // 这里可以触发退出的 action
        break;
      case 403:
        message = "拒绝访问";
        break;
      case 404:
        message = "请求地址错误";
        break;
      case 500:
        message = "服务器故障";
        break;
      default:
        message = "网络连接故障";
    }

    alert(message);
    return Promise.reject(error);
  }
);
/* 导出封装的请求方法 */
export const http = {
  get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config);
  },

  post<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config);
  },

  put<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config);
  },

  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config);
  },
};
